import re

from lib.base.trigger import baseStnTrigger
from lib.utils.utils import *

class regexStnTrigger(baseStnTrigger):
    def run(self):
        # init param with default value or from config file
        type = self.jsonCfg.evalGet(self.trig, 'type', 'trig')
        regex = self.jsonCfg.evalGet(self.trig, 'regex')
        fIn = self.jsonCfg.evalGet(self.trig, 'in')
        inIsLink = self.jsonCfg.evalGet(self.trig, 'in_is_link')
        fOut = self.jsonCfg.evalGet(self.trig, 'out')
        dest = int(self.jsonCfg.evalGet(self.trig, 'dest'))
        cs = self.jsonCfg.evalGet(self.trig, 'cs')
        justMached = self.jsonCfg.evalGet(self.trig, 'justmached')
        htmlEntities = self.jsonCfg.evalGet(self.trig, 'html_entities')
        noclean = self.jsonCfg.evalGet(self.trig, 'noclean')
        clear = self.jsonCfg.evalGet(self.trig, 'clear')
        
        self.logger.log(logging.DEBUG_01,"type: %s, regex: %s, in: %s, in_is_link: %s, out: %s, dest: %s, cs: %s, justmached: %s, html_entities: %s, noclean: %s, clear: %s)" 
                         % (type, regex, fIn, inIsLink, fOut, dest, cs, justMached, htmlEntities, noclean, clear))
        
        # call real trigger function
        return self.__trig(regex, fIn, inIsLink, fOut, dest, cs, justMached, htmlEntities, noclean, clear)
        
    def __trig(self, regex, fIn, inIsLink, fOut, dest, cs, justMached, htmlEntities, noclean, clear):
        # get and format input (interpolate with buffer)
        input = fIn.format(*self.buffer)
        
        # input is link
        if(inIsLink is True):
            self.logger.log(logging.DEBUG_01, "Get url '%s'" % input)
            input = getPage(input, self.userAgent)

        defaultReFlags = re.DOTALL
        
        # not case sensitive
        if(cs is False):
            defaultReFlags |= re.IGNORECASE
  
        match = re.search(regex, input, defaultReFlags)
        
        # matched something
        if(match):
            self.logger.log(logging.DEBUG_01,"Matched! :)")
            
            output = None
            # there are sub-group
            if(match.lastindex is not None):
                # backslash substitution 
                output = match.expand(fOut)
                self.logger.log(logging.DEBUG_02,"Matched > groups expanded output: %s" % output)
            else:
                output = match.group(0)
                self.logger.log(logging.DEBUG_02,"Matched > string: %s" % output)
            
            # html entities decode    
            if(htmlEntities is True):
                output = htmlEntityDecode(output)

            # strip html tags
            if(noclean is False):
                output = re.sub('<[^>]*>', '', output)

            # set output buffer
            self.buffer[dest] = output
            
            # check if input is "justmatched" in the past
            if(justMached is not None and self.justMatchedObj.check(input, justMached) is True):
                self.logger.log(logging.DEBUG,"Not respect justmached %s seconds" % justMached)
                return False
            
            super().callTrigger()
            super().callNotifier()
            
            return True
        else:
            self.logger.log(logging.DEBUG,"Not Matched! :(")
            
            # clear buffer if not match
            if(clear is True):
                self.buffer[dest] = ''
                
            return False